package coupon

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"bp/internal/util"
	"context"
	"database/sql"
)

// EnsureCouponStatParam 确保CouponStat参数
type EnsureCouponStatParam struct {
	CouponPtr *sqlc.Coupon
	CouponID  int64
}

// EnsureCouponStat 确保CouponStat对一张券始终有一条记录并返回
func (s *CouponEntityServiceImp) EnsureCouponStat(ctx context.Context, q *sqlc.Queries, withLock bool, ptr *EnsureCouponStatParam) (couponStatPtr *sqlc.CouponStat, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	var couponPtr *sqlc.Coupon
	if ptr.CouponPtr != nil {
		couponPtr = ptr.CouponPtr
	} else {
		couponPtr, err = s.GetCouponPtr(ctx, q, ptr.CouponID)
		if err != nil {
			return
		}
		slog.Infof("0 GetCouponPtr ok")
	}
	couponID := couponPtr.ID

	var sqlErr error
	var couponStat sqlc.CouponStat
	if withLock {
		couponStat, sqlErr = q.GetCouponStatByCouponIDToLock(ctx, couponID)
	} else {
		couponStat, sqlErr = q.GetCouponStatByCouponID(ctx, couponID)
	}

	if sqlErr != nil {
		if sql.ErrNoRows != sqlErr {
			err = sqlErr
			return
		}
		couponStat, err = q.UpsertCouponStat(ctx, sqlc.UpsertCouponStatParams{
			BrandID:  couponPtr.BrandID,
			CouponID: couponID,
		})
		if err != nil {
			return
		}
	}
	couponStatPtr = &couponStat
	slog.Infof("确保CouponStat对一张券始终有一条记录并返回 ok")
	return
}

// RefreshCouponStatSinceMemberGotCoupon C端用户领取优惠券刷新券统计
func (s *CouponEntityServiceImp) RefreshCouponStatSinceMemberGotCoupon(ctx context.Context, q *sqlc.Queries, couponID int64) (err error) {
	// slog := util.NewContextLogger(ctx, s.slog)

	err = q.UpdateCouponStatGotCnt(ctx, couponID)
	if err != nil {
		return
	}

	// slog.Infof("C端用户领取优惠券刷新券统计 ok")
	return
}
